var wsProtocol = (location.protocol === "https:") ? "wss://" : "ws://";

var ws = new WebSocket(wsProtocol + location.host + "/image");
ws.binaryType = 'arraybuffer';
var data;
ws.onmessage = (evt) => {
	data = new Uint8Array(evt.data);
	document.getElementById("liveImg").src = window.URL.createObjectURL(new Blob([data], { type: "image/jpeg" }));
}


function stop(){
	fetch("/control/stop", { method : "POST",
				 headers : {"Content-Type" : "application/json"},
				 body : JSON.stringify({stop : 1})
	}).then(function (res){ if(res.status !== 200) alert("alert stop!"); });
}

function move(axis, direction){
	fetch("/control/move", { method : "POST",
				 headers : {"Content-Type" : "application/json"},
				 body : JSON.stringify({axis : axis, dir : direction})
	}).then(function (res){ if(res.status !== 200) alert("alert move!"); });
}

function rotate(direction){
	fetch("/control/rotate", { method : "POST",
				   headers : {"Content-Type" : "application/json"},
				   body : JSON.stringify({dir : direction})
	}).then(function (res){ if(res.status !== 200) alert("alert rotate!"); });
}

function signal(){
	fetch("/control/signal", { method : "POST",
				   headers : {"Content-Type" : "application/json"},
				   body : JSON.stringify({signal : 1})
	}).then(function (res){ if(res.status !== 200) alert("alert signal!"); });
}


document.addEventListener('keydown', function (event){
	const key = event.key;
	switch(key){
		case "w":
			move(1,1)
		case "s":
			move(1,0)
		case "a":
			move(0,0)
		case "d":
			move(0,1)
		case "ArrowLeft":
			rotate(0)
		case "ArrowRight":
			rotate(1)
	}
})

//document.addEventListener('keyup', function (event){
//	const key = event.key;
//	switch(key){
//		case "w':
//			stop()
//		case "a":
//			stop()
//		case "s":
//			stop()
//		case "d":
//			stop()
//	}
//})
